import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Data, Router} from '@angular/router';
import {PublicService} from '../../services/public.service';
import {VariationService} from '../variation.service';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService} from 'primeng/primeng';
import {BasePage} from '../../base.page';
import {PUblicMethod} from '../../services/PUblicMethod';
import {VariationObjModel} from '../variationObj.model';
import {UnvariationTableComponent} from '../public/unvariation-table/unvariation-table.component';
import {TimeNotSameValidator} from '../../validator/validators';
import {CapacityDialogComponent} from '../../public/capacity-dialog/capacity-dialog.component';
import {SelectEquipmentsComponent} from '../../public/select-equipments/select-equipments.component';

@Component({
  selector: 'app-create-edit-variation',
  templateUrl: './create-edit-variation.component.html',
  styleUrls: ['./create-edit-variation.component.scss']
})
export class CreateEditVariationComponent extends BasePage implements OnInit {

    @ViewChild('unvariationTable') unvariationTable: UnvariationTableComponent;
    @ViewChild('capacityDialog') capacityDialog: CapacityDialogComponent;
    @ViewChild('selectEquipments') selectEquipments: SelectEquipmentsComponent;
    formTitle = '创建申请单';
    controlDiaglog: boolean;
    myForm: FormGroup;
    formObj: VariationObjModel;
    allTypes: Array<object>;
    allApprovals: Array<object>;
    zh: any;
    showAddMask: boolean = false;
    displayCapcity: boolean = false;
    minEndTime: Date;
    displayPersonel: boolean = false;              // 人员组织组件是否显示
    totalRecords;
    dataSource;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private publicService: PublicService,
                private variationService: VariationService,
                public messageService: MessageService,
                public confirmationService: ConfirmationService) {
        super(confirmationService, messageService);
    }

    ngOnInit() {
        this.formObj = new VariationObjModel();
        this.zh = new PUblicMethod().initZh();
        this.initMyForm();
        this.formObj.plan_time_begin = PUblicMethod.formateEnrtyTime(new Date());
        this.formObj.plan_time_end = PUblicMethod.formateEnrtyTime(new Date());
        this.minEndTime = new Date();
        this.controlDiaglog = false;
        // this.initCreator();
        this.initRegistrationType();
        this.getApprovals('');
    }

    initMyForm = () => {
        this.myForm = this.fb.group({
            room_name: [null, Validators.required],
            timeGroup: this.fb.group({
                plan_time_begin: [null, Validators.required],
                plan_time_end: [null, Validators.required]
            }, {validator: TimeNotSameValidator}),
            content: [null, Validators.required],
            applicant: [null, Validators.required]
        });
    };

    goBack = () => {
        this.router.navigate(['../overview'], {relativeTo: this.activedRouter});
    };

    showTreeDialog = () => {
        this.displayCapcity = true;
    };

    displayCapcityEmitter = event => {
        this.displayCapcity = event;
    };

    seledtedCapcityEmitter = event => {
        this.formObj.room_name = event['label'];
        this.formObj.room_did = event['did'];
    };

    clearTreeDialog = () => {
        this.formObj.room_name = '';
        this.formObj.room_did = '';
        this.capacityDialog.clearSelected();
    };

    // initCreator = () => {
    //     this.publicService.getUser().subscribe(res => {
    //         this.formObj.creator = res['name'];
    //         this.formObj.creator_org = res['organization'];
    //     });
    // };

    getApprovals = (oid?) => {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.allApprovals = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.allApprovals = newArray;
                // this.formObj.applicant = newArray[0]['value']['name'];
                // this.formObj.applicant_pid = newArray[0]['value']['pid'];
                // this.formObj.applicant_org = newArray[0]['value']['post'];
                // this.formObj.applicant_org_oid = newArray[0]['value']['oid'];

                this.formObj.approve = newArray[0]['value']['name'];
                this.formObj.approve_pid = newArray[0]['value']['pid'];
                this.formObj.approve_org = newArray[0]['value']['post'];
                this.formObj.approve_org_oid = newArray[0]['value']['oid'];
            }
            this.getQueryParams();
        });
    }

    switchApplicant = event => {
        if (typeof this.formObj.applicant === 'object') {
            this.formObj.applicant_pid = this.formObj.applicant['pid'];
            this.formObj.applicant_org = this.formObj.applicant['post'];
            this.formObj.applicant_org_oid = this.formObj.applicant['oid'];
            this.formObj.applicant = this.formObj.applicant['name'];
        }
    }

    initRegistrationType = () => {
        this.allTypes = [
            {
                'label': '电力调整',
                'value': '电力调整'
            },
            {
                'label': '位置设置',
                'value': '位置设置'
            },
            {
                'label': '其他',
                'value': '其他'
            }
        ];
        this.formObj.adjust_type = '电力调整';
    };

    formatPerson = () => {
        if (typeof this.formObj.approve === 'object') {
            this.formObj.approve_pid = this.formObj.approve['pid'];
            this.formObj.approve = this.formObj.approve['name'];
        }
    }

    formatTime = () => {
        this.formObj.plan_time_begin = PUblicMethod.formateEnrtyTime(this.formObj.plan_time_begin);
        this.formObj.plan_time_end = PUblicMethod.formateEnrtyTime(this.formObj.plan_time_end);
    }

    startTimeSelected = t => { this.minEndTime = t; };

    isFieldValid = (name) => {
        return PUblicMethod.isFieldValid(this.myForm, name);
    };

    // can listen fromgroup's error when formgroup nested formgroup
    isFieldFroupValid = (name?) => {
        return this.myForm.get('timeGroup').hasError('timematch');
    };

    // for button which is relative with one of formcontrol
    isFieldValueValid = (name) => {
        return PUblicMethod.isFieldValueValid(this.myForm, name);
    };

    // formgroup nested formgroup can use this
    isFieldGroupItemValid = (name) => {
        return PUblicMethod.isFieldGroupValid(this.myForm.get('timeGroup'), name);
    };

    save = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.unvariationTable.tableDatas;
        (!this.formObj.sid) && (this.requestSave());
        (this.formObj.sid) && (this.requestSaveAfterEdited());
    };

    requestSave = () => {
        this.variationService.requestSave(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`保存失败 + ${res}`, 'error');
            }
        });
    };

    requestSaveAfterEdited = () => {
        this.variationService.requestSaveAfterEdited(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('修改保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`修改保存失败 + ${res}`, 'error');
            }
        });
    };

    submit = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.unvariationTable.tableDatas;
        if (this.myForm.valid) {
            if (this.formObj.devices.length === 0) {
                this.alert('请先选择设备再进行提交', 'warn');
            }else {
                (!this.formObj.sid) && (this.requestSubmit());
                (this.formObj.sid) && (this.requestSubmitAfterEidted());
            }
        }else {
            PUblicMethod.validateAllFormFields(this.myForm);
        }
    };

    requestSubmit = () => {
        this.variationService.requestSubmite(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('提交成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`提交失败失败 + ${res}`, 'error');
            }
        });
    };

    requestSubmitAfterEidted = () => {
        this.variationService.requestSubmitAfterEdit(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('修改提交成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`修改提交失败 + ${res}`, 'error');
            }
        });
    };

    openEquipList() {
        this.controlDiaglog = true;
    }
    dcontrolDialogHandler(event) {
        this.controlDiaglog = event;
    }

    removeEquipmenst = () => {
        for (let i = 0; i < this.unvariationTable.selectedCars3.length; i++) {
            this.unvariationTable.tableDatas = this.unvariationTable.tableDatas.filter(v => {
              return !(v['ano'] === this.unvariationTable.selectedCars3[i]['ano']);
            })
        }
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.unvariationTable.tableDatas);
    }

    removeMask(bool){
        this.showAddMask = bool;
    }
    addDevice(asset){
        // this.dataSource = [];
        // this.dataSource.push(asset);
        // this.totalRecords = this.dataSource.length;
        // this.assets = this.dataSource.slice(0,10);
        // this.confirmationService.confirm({
        //     message: '添加成功！',
        //     rejectVisible:false,
        // })
    }

    selectedEquipsEmitter = event => {
      console.log(event);
      this.dataSource = event;
        event.forEach(arrayItem => {
            this.unvariationTable.tableDatas.push(arrayItem);
            this.unvariationTable.dataSource = this.unvariationTable.tableDatas;
            this.unvariationTable.totalRecords = this.unvariationTable.dataSource.length;
            this.unvariationTable.tableDatas = this.unvariationTable.dataSource.slice(0,10);
        });
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.unvariationTable.tableDatas);
    };

    getSelectedAnoArray = (data): any => {
        let anoArray = [];
        for (let i = 0; i < data.length; i++ ) {
            anoArray.push(data[i]['ano']);
        }
        return anoArray;
    }

    getQueryParams = () => {
        this.activedRouter.queryParams.subscribe(params =>  {
            (params['sid'])  && this.requestMesageBySid(params['sid']);
            // (params['status_code']) && (this.statusCode = params['status_code']);
            // (params['status']) && (this.eventBusService.accessFlowCharts.next(params['status']));
            // (params['sid'] && params['status'])  && this.requestMesageBySid(params['sid']);
        });
    };

    requestMesageBySid = id => {
        this.variationService.getMesageBySid(id).subscribe(res => {
            if (res['errcode'] === '00000') {
                this.formObj = new VariationObjModel(res['data']);
                // (res['data']['approver_pid']) && this.filterSelectedApporve(this.allApprovals, res['data']['approver_pid']);
                res['data']['devices'] ? this.unvariationTable.tableDatas = res['data']['devices'] : this.unvariationTable.tableDatas = [];
                (res['data']['devices'] && res['data']['devices']['length'] > 0) && this.getSelectedAnoArray(res['data']['devices']);
            }else {
                this.alert(`获取出入单信息失败 + ${res['errmsg']}`, 'error');
            }
        });
    };

    showPersonDialog = () => {this.displayPersonel = true; };

    clearPersonDialog = () => {
        this.formObj.applicant = '';
        this.formObj.applicant_org_oid = '';
        this.formObj.applicant_org = '';
        this.formObj.applicant_pid = '';
    };

    dataEmitter = event => {
        this.formObj.applicant = event.name;
        this.formObj.applicant_pid = event.pid;
        this.formObj.applicant_org = event.organization;
        this.formObj.applicant_org_oid = event.oid;
    };

    displayEmitter = event => { this.displayPersonel = event; };
}
